import { action, makeAutoObservable, observable, toJS } from 'mobx'

import AsyncStorage from '@react-native-async-storage/async-storage'

const historyKey = 'search:history'
const historyMaxSize = 15

export default class Search {
  placeholder = ''
  hotspot = []

  history = []

  constructor() {
    makeAutoObservable(this, {
      placeholder: observable,
      hotspot: observable,
      history: observable,
      setPlaceholder: action,
      setHotspot: action,
      appendHistory: action,
      clearHistory: action,
    })

    AsyncStorage.getItem(historyKey).then(data => {
      this.history = JSON.parse(data) || []
    })
  }

  setPlaceholder = ph => {
    this.placeholder = ph
  }

  setHotspot = (hs) => {
    this.hotspot = hs
  }

  appendHistory = (h) => {
    if (typeof h != 'string') {
      return
    }

    let history = toJS(this.history)
    if (history.indexOf(h) != -1) {
      history = history.filter(it => it != h)
    } 

    history = [h, ...history]
    history = history.length > historyMaxSize ? history.slice(0, historyMaxSize) : history

    AsyncStorage.setItem(historyKey, JSON.stringify(history))
    this.history = history
  }

  clearHistory = () => {
    this.history = []
    AsyncStorage.removeItem(historyKey)
  }
}